var config = require('../../utils/config');
var util = require('../../utils/util');
var db = require('../../utils/db');
//获取应用实例
var app = getApp()
Page({
  data: {
    isLogin:false,
    userInfo:{},
    meList:[
      {
        text:'我的班级',
        icon:'../../assets/img/iconfont-kefu.png',
        url:'../class/class'
      },
      {
        text:'我的图书',
        icon:'../../assets/img/iconfont-dingdan.png',
        url:'../bookList/bookList'
      },
      {
        text:'联系客服',
        icon:'../../assets/img/iconfont-help.png',
        url:''
      }
    ]
  },
  onShow:function() {
    var that = this;
    let userInfo = wx.getStorageSync('user');
    if (userInfo!=null&&userInfo!=undefined&&userInfo!={}&&userInfo!='') {
      that.setData({
        isLogin:true,
        userInfo:userInfo
      })
    }else {
      //调用应用实例的方法获取全局数据
      app.getUserInfo(function(userInfo) {
        setTimeout(()=>{
          userInfo = wx.getStorageSync('user');
          if (userInfo.userId) {
            that.setData({
              isLogin:true
            })
          }
          //更新数据
          that.setData({
            userInfo:userInfo
          })
        }, 2000);
      })
    }
  },
  getPhoneNumber(e) {
    if(e.detail.errMsg == 'getPhoneNumber:fail user deny'){//拒绝获取手机号
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '未授权',
        success: function (res) {}
      })
    }else if(e.detail.errMsg.indexOf('getPhoneNumber:fail Error')>=0){//不支持获取手机号
    }else {//同意获取手机号
      var that = this;
      wx.login({
        success: function (resLogin) {
          let code = resLogin.code;
          wx.getUserInfo({
            success: function (res) {
              that.setData({
                isLogin:true,
                userInfo:res.userInfo
              })
              db.putOpenid(code, (resOpen, err) => {
                if (resOpen.data.data.userId) {
                  app.setUserInfo(resOpen.data.data);
                  setTimeout(()=>{
                    that.data.userInfo = wx.getStorageSync('user');
                    that.onShow();
                  }, 2000);
                }else {
                  let openId = resOpen.data.data.openid;
                  var option = {
                    method: 'GET',
                    url: config.clubApi.getPhone,
                    data: {
                      encryptedData: e.detail.encryptedData,
                      iv: e.detail.iv,
                      sessionKey: resOpen.data.data.sessionKey,
                      openid: openId
                    }
                  };
                  util.request(option, (res) => {
                    if (res.statusCode===200) {
                      app.queryUser(openId);
                      setTimeout(()=>{
                        that.data.userInfo = wx.getStorageSync('user');
                        that.onShow();
                      }, 2000);
                    }else {
                      that.setData({
                        isLogin:false,
                        userInfo:{}
                      })
                    }
                  });
                }                
              });
            }
          })
        }
      })
    }
  },
  onChooseAvatar:function(e) {
    var that = this;
    let userInfo = wx.getStorageSync('user');
    if (that.data.isLogin) {
      if (e.detail.avatarUrl!=undefined&&e.detail.avatarUrl!=null&&e.detail.avatarUrl!=''&&
        userInfo.userId!=undefined&&userInfo.userId!=null&&userInfo.userId!='') {
        that.updateUseravatar(userInfo.userId, e.detail.avatarUrl);
      }else if (userInfo.userId!=undefined&&userInfo.userId!=null&&userInfo.userId!='') {
        wx.chooseImage({
          count: 1, // 默认9
          sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
          success: function (res) {
            that.updateUseravatar(userInfo.userId, res.tempFilePaths);
          }
        })
      }
    }else {
      if (userInfo.userId==undefined||userInfo.userId==null||userInfo.userId=='') {
        app.getUserInfo(function(userInfo) {
          setTimeout(()=>{
            userInfo = wx.getStorageSync('user');
            //更新数据
            that.setData({
              isLogin:true,
              userInfo:userInfo
            })
          }, 2000);
        })
      }
    }
  },
  updateUseravatar:function (userId, userAvatar) {
    var that = this;
    let userInfo = wx.getStorageSync('user');
    wx.uploadFile({
      url: config.clubApi.putAvatar,
      method: 'POST',
      filePath: userAvatar,
      name: 'file',
      header: {  
        'Content-Type': 'multipart/form-data'                    
      },
      formData: {
        'userId': userId
      },
      success (res){
        if (res.statusCode===200) {
          let json = JSON.parse(res.data);
          userInfo.avatar = json.data;
          wx.setStorageSync('user', userInfo);
          that.setData({userInfo:userInfo});
          util.showSuccess('设置成功!', config.showSuccessTime, () => {
            that.onShow();
          })
        }
      }
    })
  },
  // 退出登录
  loginOut() {
      this.setData({
        isLogin:false,
        userInfo:{}
      })
      // 清空缓存
      wx.setStorageSync('user',null);
  },
  toMyinfo: function() {
    wx.navigateTo({
      url: '../myeditm/myeditm'
    });
  }
})
